using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Dimok.Aspx.Manager.Lib;
using AOs = AcrobatObjects;
using Dimok;
using Dimok.Exceptions;
using Dimok.Images;
using Data;

namespace Dimok.Aspx.Manager.Common {
	public partial class DocsList : System.Web.UI.Page {
		protected void Page_Load(object sender, System.EventArgs e) {
			UOX uox = new UOX();
			string docsPath = HttpEx.MapPath(Reg.Forms.Path);
			if( !IsPostBack ){
				StringCollection fileList = new StringCollection();
				fileList.AddRange(Directory.GetFiles(docsPath,"*.doc"));
				fileList.AddRange(Directory.GetFiles(docsPath,"*.pdf"));
				rptDocs.DataSource = fileList;
				rptDocs.DataBind();
				hdnApplID.Value = uox.applID+"";
				return;
			}
			byte[] file = null;
			string fileName = "";
			try{
				string[] fileNames = Request.Form.GetValues("FileName");
				for( int i = 0; i < fileNames.Length; i++ )
					fileNames[i] = FileManager.FindFiles(HttpEx.MapPath(docsPath),fileNames[i]+".*")[0];
				string sql = "SELECT * FROM vform_Base WHERE "+uox.ApplicantFilter();
				DataSet dsForm = SQL.ExecuteDatasetEx(uox.db,sql);
				if( dsForm.Tables[0].Rows.Count == 0 )throw new ClientException("Applicant "+uox.applID+" does not exist.");
				DataRow rowForm = dsForm.Tables[0].Rows[0];
				file = AOs.AcrobatClient.FillPDFForm(FileManager.GetBytesFromFile(fileNames),SQL.RowToHashTable(rowForm));
				fileName = rowForm["FirstName"]+""+rowForm["LastName"]+"."+Enums.GetExtention(file);
			}catch(Exception exc){
				throw new ASPException(exc);
			}
			//Thread.Sleep(1000);
			Response.Cache.SetMaxAge(new TimeSpan(0,0,Reg.Forms.MaxAge));
			Response.ContentType = Enums.GetContentType(file);//"Application/msword";
			Response.AddHeader("content-disposition","attachment; filename=\""+fileName+"\"");
			Response.BinaryWrite(file);
			this.Visible = false;
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e) {
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent() {    

		}
		#endregion
	}
}
